import axios from 'axios'
import { toast } from '@/utils'
import store from '../store'
/** 错误处理 */
const handleError = (data) => {
  switch (data.code) {
    case 400:
      toast.fail(data.message)
      break

    case 401:
      toast.fail(data.message)
      window.location.href = '/login'
      break
    case 403:
      toast.fail(data.message)
      window.location.href = '/login'
      break
    case 404:
      toast.fail(data.message)
      break
  }
}

/** 封装axios */
const http = (config) => {
  const instance = axios.create({
    baseURL: 'http://localhost:3000/',
    timeout: 5000
  })

  // 请求拦截
  instance.interceptors.request.use((config) => {
    /*给请求头添加token  */
    config.headers['authorization'] = store.state.token
    // 序列化
    // 添加Loading
    return config
  })

  // 响应拦截
  instance.interceptors.response.use(
    (response) => {
      if (response.data.code === 200) return response.data
      else handleError(response.data)
    },
    (error) => {
      handleError(error.response.data)
    }
  )

  return instance(config)
}

export default http
